import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

const routes = [
    {
        path: '*',
        redirect: '/index'
    },
    {
        path: '/login',
        component: () => import('./view/login/login'),
        meta: {
            title: '登录',
            isLogin: false
        }
    },
    {
        path: '/index',
        component: () => import('./view/work/index'),
        meta: {
            title: '首页',
            isLogin: true
        }
    },
    {
        path: '/app/:id',
        component: () => import('./view/app/appTaskList'),
        meta: {
            title: '应用',
            isLogin: true
        }
    }
];

// add route path
routes.forEach(route => {
    route.path = route.path || '/' + (route.name || '');
});

const router = new Router({routes});

router.beforeEach((to, from, next) => {
    const title = to.meta && to.meta.title;
    if (title) {
        document.title = title;
    }
    //先判断store里accessToken是否为空，如果不为空，代表已经登录，继续执行；
    // 如果为空，就判断localStorage的accessToken是否为空，如果不为空，给store里accessToken赋值，继续执行；
    //如果localStorage的accessToken为空，提示用户重新登录

    let accessToken = localStorage.getItem("accessToken");
    if (accessToken) {
        next();
    } else {
        if (to.meta.isLogin) {
            next({
                path: '/login'
            })
        } else { //匿名访问可以不登录访问
            next()
        }
    }


});


export {
    router
};
